<!--
 * @Author: Dorange.Wang
 * @Date: 2021-05-13 11:00:36
 * @LastEditors: your name
 * @LastEditTime: 2021-09-07 09:35:42
 * @Description: file content
-->
<template>
  <div class="">
    <el-form
      class="http-service_env-form"
      :model="dynamicValidateForm"
      ref="dynamicValidateForm"
      label-width="120px"
    >
      <el-form-item
        label="服务地址"
        prop="serverUrl"
        :rules="[
          {
            required: fieldRequired,
            message: '服务地址不能为空',
            trigger: 'change',
          },
          {
            pattern: URL_REG,
            message: '请输入有效的服务地址',
            trigger: 'change',
          },
        ]"
      >
        <el-input
          v-model="dynamicValidateForm.serverUrl"
          placeholder="请输入服务地址"
          :maxlength="128"
          show-word-limit
        ></el-input>
      </el-form-item>

      <template v-if="['MOS', 'HAN_CODE'].includes(authType)">
        <el-form-item
          label="AppId"
          prop="appId"
          :rules="[
            {
              required: fieldRequired,
              message: 'AppId不能为空',
              trigger: 'change',
            },
          ]"
        >
          <el-input
            v-model="dynamicValidateForm.appId"
            placeholder="请输入AppId"
            :maxlength="64"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="AppSecret"
          prop="appSecret"
          :rules="[
            {
              required: fieldRequired,
              message: 'AppSecret不能为空',
              trigger: 'change',
            },
          ]"
        >
          <el-input
            v-model="dynamicValidateForm.appSecret"
            placeholder="请输入AppSecret"
            :maxlength="128"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>

      <template v-if="authType === 'HAN_CODE' && env === 'DEV'">
        <el-form-item
          label="AppUnique"
          prop="appUnique"
          :rules="[
            {
              required: fieldRequired,
              message: 'AppUnique不能为空',
              trigger: 'change',
            },
          ]"
        >
          <el-input
            v-model="dynamicValidateForm.appUnique"
            placeholder="请输入AppUnique"
            :maxlength="64"
            show-word-limit
          ></el-input>
        </el-form-item>
      </template>

      <template v-if="authType === 'TOKEN'">
        <el-form-item
          label="认证地址"
          prop="tokenUrl"
          :rules="[
            {
              required: fieldRequired,
              message: '认证地址不能为空',
              trigger: 'change',
            },
            {
              pattern: URL_REG,
              message: '请输入有效的认证地址',
              trigger: 'change',
            },
          ]"
        >
          <el-input
            v-model="dynamicValidateForm.tokenUrl"
            placeholder="请输入认证地址"
            :maxlength="128"
            show-word-limit
          >
            <el-select
              style="width: 90px"
              v-model="dynamicValidateForm.tokenMethod"
              slot="prepend"
              placeholder="请选择"
            >
              <el-option label="GET" value="GET"></el-option>
              <el-option label="POST" value="POST"></el-option>
              <el-option label="PUT" value="PUT"></el-option>
            </el-select>
          </el-input>
        </el-form-item>

        <el-form-item
          label="Token取值"
          prop="tokenPath"
          :rules="[
            {
              required: fieldRequired,
              message: 'Token取值不能为空',
              trigger: 'change',
            },
          ]"
        >
          <template slot="label"
            >Token取值
            <el-tooltip
              popper-class="custom-popper"
              content="请使用JsonPath表达式"
              placement="top"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <el-input
            v-model="dynamicValidateForm.tokenPath"
            placeholder="请输入Token取值"
            :maxlength="128"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item
          label="Token有效期"
          prop="tokenExpire"
          :rules="[
            {
              required: fieldRequired,
              message: 'Token有效期不能为空',
              trigger: 'change',
            },
          ]"
        >
          <el-input
            style="width: 50%"
            class="mr10"
            v-model="dynamicValidateForm.tokenExpire"
            placeholder="请输入Token有效期"
            :maxlength="9"
          ></el-input>
          分钟
        </el-form-item>
      </template>

      <el-form-item
        v-if="hasCustomParams"
        label="参数"
        :required="fieldRequired"
        style="margin-bottom: 0px"
      >
        <el-button type="text" @click="handleParamsAdd">添加参数</el-button>
      </el-form-item>

      <el-form-item
        v-if="hasCustomParams"
        label=""
        label-width="0px"
        prop="params"
        :rules="[
          {
            required: fieldRequired,
            message: '参数不能为空',
            trigger: 'change',
          },
        ]"
      >
        <el-table
          class="http-service_env-table"
          :data="dynamicValidateForm.params"
          style="width: 100%"
          stripe
          border
          row-key="id"
        >
          <!-- 这里用不同的prop去渲染参数名 否则切换有bug -->
          <!-- <el-table-column v-if="authType === 'MOS'" prop="mosName" label="参数名" width="120" >
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column> -->
          <el-table-column prop="name" label="参数名" width="200">
            <!-- <template v-if="authType === 'MOS'" slot="header">
              参数值
              <el-tooltip popper-class="custom-popper" content="内置类型参数值格式为：${value}" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </template> -->
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'params.' + scope.$index + '.name'"
                :rules="[
                  {
                    required: fieldRequired,
                    message: '参数名不能为空',
                    trigger: 'change',
                  },
                  { validator: nameValidator, trigger: 'change' },
                ]"
              >
                <el-input
                  v-model="scope.row.name"
                  placeholder="请输入参数名"
                  :maxlength="64"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="value" label="参数值">
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'params.' + scope.$index + '.value'"
                :rules="[
                  {
                    required: fieldRequired,
                    message: '参数值不能为空',
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.value"
                  placeholder="请输入参数值"
                  :maxlength="200"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="actions" label="操作" width="80">
            <template slot-scope="scope">
              <span class="table-actionItem">
                <el-button
                  class="link-danger"
                  type="text"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { URL_REG } from "@/utils/reg"
import { randomString } from "@/utils/util"
export default {
  name: "HttpServiceEnvForm",
  props: {
    env: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "NATIVE",
    },
    instanceName: {
      type: String,
      default: "",
    },
    envName: {
      type: String,
      default: "",
    },
    authType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      URL_REG,
      dynamicValidateForm: {
        serverUrl: "",
        tokenMethod: "GET",
        tokenUrl: "",
        tokenPath: "",
        tokenExpire: undefined,
        params: [],
        appId: "",
        appSecret: "",
        appUnique: "",
      },
    }
  },

  computed: {
    fieldRequired() {
      const {
        serverUrl,
        tokenUrl,
        tokenPath,
        tokenExpire,
        params,
        appId,
        appSecret,
        appUnique,
      } = this.dynamicValidateForm
      const hasServerUrl = (serverUrl || "").trim().length > 0
      const hasTokenUrl = (tokenUrl || "").trim().length > 0
      const hasTokenPath = (tokenPath || "").trim().length > 0
      const hasTokenExpire = (tokenExpire || "").trim().length > 0
      const hasParams = params.length > 0
      const hasAppId = (appId || "").trim().length > 0
      const hasAppSecret = (appSecret || "").trim().length > 0
      const hasAppUnique = (appUnique || "").trim().length > 0
      return (
        this.type === "CLOUD" ||
        this.env === "DEV" ||
        hasServerUrl ||
        hasTokenUrl ||
        hasTokenPath ||
        hasTokenExpire ||
        hasAppId ||
        hasAppSecret ||
        hasAppUnique ||
        hasParams
      )
    },

    hasCustomParams() {
      return ["PASS_THROUGH", "TOKEN"].includes(this.authType)
    },
  },

  watch: {
    authType(newVal, oldVal) {
      this.dynamicValidateForm = {
        serverUrl: "",
        tokenMethod: "GET",
        tokenUrl: "",
        tokenPath: "",
        tokenExpire: undefined,
        params: [],
        appId: "",
        appSecret: "",
        appUnique: "",
      }
      this.$nextTick(() => {
        this.$refs.dynamicValidateForm.clearValidate()
      })
    },
  },

  methods: {
    setData(data = {}) {
      if (this.authType === "MOS" || this.authType === "HAN_CODE") {
        const appDataList = data.json ? JSON.parse(data.json) : []
        const appDataMap = {}
        if (!appDataList.length) {
          this.dynamicValidateForm = {
            serverUrl: "",
            tokenMethod: "GET",
            tokenUrl: "",
            tokenPath: "",
            tokenExpire: undefined,
            params: [],
            appId: "",
            appSecret: "",
            appUnique: "",
          }
        }
        appDataList.forEach((item) => {
          appDataMap[item.name] = item.value
          this.dynamicValidateForm = {
            ...data,
            ...appDataMap,
            params: [],
            tokenMethod: data.tokenMethod || "GET",
          }
        })
      } else {
        this.dynamicValidateForm = {
          ...data,
          params: data.json ? JSON.parse(data.json) : [],
          tokenMethod: data.tokenMethod || "GET",
        }
      }
      this.$nextTick(() => {
        this.$refs.dynamicValidateForm.clearValidate()
      })
    },

    nameValidator(rule, value, callback) {
      const names = this.dynamicValidateForm.params.map((item) => item.name)
      if (names.filter((name) => name === value).length > 1) {
        callback(new Error("参数已存在"))
      } else {
        callback()
      }
    },

    handleParamsAdd() {
      const id = randomString(8)
      const item = {
        id,
        name: "",
        value: "",
      }
      this.dynamicValidateForm.params.push(item)
    },

    /**
     * 初始化mos认证的参数
     */
    // handleMosParamsInit () {
    //   const params = [
    //     {
    //       id: randomString(8),
    //       name: 'appId',
    //       value: ''
    //     },
    //     {
    //       id: randomString(8),
    //       name: 'appSecret',
    //       value: ''
    //     }
    //   ]
    //   this.dynamicValidateForm.params = params
    // },

    genParams(params) {
      return Object.keys(params).map((name) => {
        return {
          id: randomString(8),
          name,
          value: params[name],
        }
      })
    },

    handleDelete(record) {
      this.dynamicValidateForm.params = this.dynamicValidateForm.params.filter(
        (item) => item.id !== record.id
      )
    },

    async getData() {
      try {
        await this.$refs.dynamicValidateForm.validate()
        const {
          serverUrl,
          tokenUrl,
          params,
          tokenMethod,
          tokenPath,
          tokenExpire,
          appId,
          appSecret,
          appUnique,
        } = this.dynamicValidateForm
        const { env, type, instanceName, envName } = this
        const setting = {
          serverUrl,
          tokenMethod,
          tokenUrl,
          env,
          type,
          instanceName,
          envName,
          json: params.length > 0 ? JSON.stringify(params) : "",
          tokenPath,
          tokenExpire,
        }
        for (const key in setting) {
          setting[key] = (setting[key] || "").trim()
        }
        if (this.authType === "MOS") {
          setting.json = JSON.stringify(
            this.genParams({
              appId,
              appSecret,
            })
          )
        } else if (this.authType === "HAN_CODE") {
          setting.json = JSON.stringify(
            this.genParams({
              appId,
              appSecret,
              appUnique,
            })
          )
        }
        return setting
      } catch (error) {
        console.log(error)
        return false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.http-service_env-table ::v-deep .el-form-item {
  margin-bottom: 0;
}
</style>
